#include <pipeOperate.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int pipeOperateInit(struct pipeOperateBaseInform *pipopt, const char *pipfile)
{
    if(!pipopt || !pipfile)
    {
        logerror("");
        return -1;
    }
    memcpystr(pipopt->pipeFileStr, sizeof(pipopt->pipeFileStr), pipfile);
    logdebug("%s : %s", pipopt->pipeFileStr, pipfile);
    mkfifo(pipopt->pipeFileStr, S_IFIFO | 0666);
    pipopt->pipeFd = open(pipopt->pipeFileStr, O_RDWR);
    if (pipopt->pipeFd < 0)
    {
        logerror("open pipe err:%s", pipopt->pipeFileStr);
        return -2;
    }
    set_fd_nonblock(pipopt->pipeFd);
    logdebug("open:%s,ok:%d", pipopt->pipeFileStr, pipopt->pipeFd);
    return 0;
}

int pipeOperateRead(struct pipeOperateBaseInform *pipopt, char *data, int datasize)
{
    if(!pipopt || !data)
    {
        logerror("");
        return -1;
    }
    if(pipopt->pipeFd <= 0)
    {
        logerror("");
        return -2;
    }
    return read(pipopt->pipeFd, data, datasize);
}
int pipeOperateWrite(struct pipeOperateBaseInform *pipopt, const char *data, int datasize)
{
    if(!pipopt || !data)
    {
        logerror("");
        return -1;
    }
    if(pipopt->pipeFd <= 0)
    {
        logerror("");
        return -2;
    }
    return write(pipopt->pipeFd, data, datasize);
}
int pipeOperateQuit(struct pipeOperateBaseInform *pipopt)
{
    if(!pipopt)
    {
        logerror("");
        return -1;
    }
    if(pipopt->pipeFd <= 0)
    {
        logerror("");
        return -2;
    }
    close(pipopt->pipeFd);
    pipopt->pipeFd = -1;
    return -1;
}


